from sqlalchemy import select
from sqlalchemy.orm import Session

from app.models import ResourceHistoryData
from common.time import str_to_datetime


def save_data(db: Session, resource_id: str, data: dict, data_time: str):
    rhd = ResourceHistoryData(
        resource_id=resource_id, data=data.get('data'), data_time=str_to_datetime(data_time)
    )
    db.add(rhd)
    db.commit()


def get_data(db: Session, resource_id: str, start_time: str, end_time: str):
    ret_data = []
    find_sql = (
        select(ResourceHistoryData)
        .where(ResourceHistoryData.resource_id == resource_id)
        .where(ResourceHistoryData.data_time >= start_time)
        .where(ResourceHistoryData.data_time <= end_time)
        .order_by(ResourceHistoryData.data_time.desc())
    )
    results = db.scalars(find_sql).all()
    for result in results:
        ret_data.append(
            {
                "resourceId": result.resource_id,
                "data": result.data,
                "dateTime": result.data_time,
            }
        )
    return ret_data
